package com.loie.xcx.util;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.loie.xcx.model.dto.IwFlow;
import com.loie.xcx.model.dto.Module_Field;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
public
class Workflow {
    public static List<IwFlow> iwFlowList = new ArrayList<IwFlow>();
    public static List<Module_Field> module_arraylist=new ArrayList<Module_Field>();
//    @Autowired
//    TaxCloudConfig taxCloudConfig;
     private static String filename;

    @Value("${taxcloud.iprojpath}") // 从application.yml配置文件中获取
    public void setFilename(String filename){
        this.filename=filename;
        //System.out.println(this.filename);
    }


    public static List<Module_Field> getmodle_fieldlist(String modulename) throws DocumentException {
        SAXReader saxReader = new SAXReader();
        //String filename = "D:\\intersky\\前程\\工作流\\Project.iproj";

        //String filename=getIprojpath();
        //System.out.println(filename);
        Document doc = saxReader.read(new File(filename));
        Element rootElt = doc.getRootElement();


//        Element lNodeItem = (Element)rootElt.selectNodes("//Catalogs/Item/Modules");
        // this.getNodes(lNodeItem);
        List<Module_Field> module_fieldList = new ArrayList<Module_Field>();

        module_fieldList.clear();
        List<Element> nodes = rootElt.selectNodes("//Catalogs/Item/Modules/Item[@Name='"+modulename+"']");
        //this.getNodes(nodes.get(0),"客户产品");
        if (nodes.size() > 0) {
            Element node = nodes.get(0);
            String tablename = node.attribute("TableName").getValue();
//            System.out.println(tablename);
            List<Element> nodeList = node.selectNodes("FieldGroups/Item");
//            System.out.println(nodeList.size());
            for (int i = 0; i <=nodeList.size() - 1; i++) {

                node = nodeList.get(i);
                List<Element> fiellist = node.selectNodes("Fields/Item");
                //System.out.println(fiellist.size());
                for (int j = 0; j<=fiellist.size() - 1; j++) {
                    Element fieldnode = fiellist.get(j);
                    Module_Field module_field = new Module_Field();
                    if (!StringUtils.isEmpty(node.attribute("IsTable"))){
                        Element node1 =(Element)node.selectSingleNode("DBProperties");

                        module_field.setTablename(node1.attribute("TableName").getValue());
                        module_field.setIstable(true);
                        module_field.setModule_field_name(modulename+"."+node.attribute("Name").getValue()+"."+fieldnode.attribute("Name").getValue());
                    }
                    else {
                        module_field.setTablename(tablename);
                        module_field.setModule_field_name(modulename+"."+fieldnode.attribute("Name").getValue());
                        module_field.setIstable(false);
                    }

                    module_field.setName(fieldnode.attribute("Name").getValue());
                    Element node2=null;
                    if (!StringUtils.isEmpty(fieldnode.selectSingleNode("Caption/Item[@Language='$00000804']"))){
                    node2= (Element) fieldnode.selectSingleNode("Caption/Item[@Language='$00000804']");
                    module_field.setTitle(node2.attribute("Text").getValue());}
                    else
                        module_field.setTitle(fieldnode.attribute("Name").getValue());


                    Element node1 = (Element) fieldnode.selectSingleNode("DataProperties");
                    module_field.setFieldname(node1.attribute("FieldName").getValue());
                    if (!StringUtils.isEmpty(node1.attribute("DataType")))
                        module_field.setDatatype(node1.attribute("DataType").getValue());
                    else
                        module_field.setDatatype("ftstring");

                    module_fieldList.add(module_field);

                }

            }
            //System.out.println(module_fieldList);
        }
        return module_fieldList;
    }

    public static
    List<IwFlow> find_nextlevel(Element rootElt, String unitname) {
        boolean isfind = false;
        if (unitname.equals("EndUnit")) return null;

        List<IwFlow> userList = new ArrayList<IwFlow>();
        userList = iwFlowList.stream().filter(user -> unitname.equals(user.getUnitName())).collect(Collectors.toList());
        if (userList.size() > 0)
            return null;

        // Element lNodeList = (Element) rootElt.selectSingleNode("/data/TcxFlow/Objects/TcxFlowStartUnit");
        List<Element> ActivityNodeList = rootElt.selectNodes("/data/TcxFlow/Objects/TcxFlowActivityUnit");
        for (int i = 0; i <= ActivityNodeList.size() - 1; i++) {
            Element lNodeItem = ActivityNodeList.get(i);
//            System.out.println("00"+unitname);
            if (lNodeItem.selectSingleNode("Name").getStringValue().equals(unitname)) {
                System.out.println("TcxFlowActivityUnit:" + unitname);
                //Optional<IwFlow> iwFlow1 = iwFlowList.stream().filter(userTemp -> unitname.equals(userTemp.getUnitName())).findFirst();


                IwFlow iwFlow = new IwFlow();
                iwFlow.setUnittype("TcxFlowActivityUnit");
                iwFlow.setUnitName(lNodeItem.selectSingleNode("Name").getStringValue());

                //temptable.FieldByName('unitcaption').AsString:= lNodeItem.selectSingleNode('Caption').text;
                //
                //            temptable.FieldByName('NextUnit').AsString:= lNodeItem.selectSingleNode('NextUnit').text;
                iwFlow.setUnitcaption(lNodeItem.selectSingleNode("Caption").getStringValue());
                iwFlow.setNextUnit(lNodeItem.selectSingleNode("NextUnit").getStringValue());
                if (!StringUtils.isEmpty(lNodeItem.selectSingleNode("OnCalcExecutorRange/Script")))
                    iwFlow.setScript(new String(Base64.decode(lNodeItem.selectSingleNode("OnCalcExecutorRange/Script").getStringValue())));
                if (!StringUtils.isEmpty(lNodeItem.selectSingleNode("ExecuteProperties"))) {
                    iwFlow.setExecutor(lNodeItem.selectSingleNode("ExecuteProperties/ExecutorRange").getStringValue());
                }

                if (!StringUtils.isEmpty(lNodeItem.selectSingleNode("RuntimeProperties"))) {
                    if (!StringUtils.isEmpty(lNodeItem.selectSingleNode("RuntimeProperties/State")))

                    iwFlow.setState(lNodeItem.selectSingleNode("RuntimeProperties/State").getStringValue());
                    if (!StringUtils.isEmpty(lNodeItem.selectSingleNode("RuntimeProperties/Level")))

                        iwFlow.setLevel(lNodeItem.selectSingleNode("RuntimeProperties/Level").getStringValue());



                    List<Element> tasklist = lNodeItem.selectNodes("RuntimeProperties/Tasks/Item");
                    Element taskitem = tasklist.get(0);
                    if (tasklist.size() > 1) taskitem = tasklist.get(tasklist.size() - 1);

                    iwFlow.setSender(taskitem.selectSingleNode("Sender").getStringValue());
                    iwFlow.setExecutor(taskitem.selectSingleNode("Executor").getStringValue());


//                    iwFlow.setExecutor(taskitem.selectSingleNode("Executor").getStringValue());
//                    iwFlow.setSender(taskitem.selectSingleNode("Sender").getStringValue());
                    if (!StringUtils.isEmpty(lNodeItem.selectSingleNode("RuntimeProperties/FlowFromUnits")))
                        iwFlow.setFlowFromUnits(lNodeItem.selectSingleNode("RuntimeProperties/FlowFromUnits").getStringValue());

                }
                iwFlowList.add(iwFlow);
                find_nextbranch(rootElt, iwFlow.getNextUnit());

                isfind = true;
                break;

            }

        }
        if (!isfind) find_nextbranch(rootElt, unitname);


        return iwFlowList;

    }

    public static
    List<IwFlow> find_nextbranch(Element rootElt, String unitname) {
        boolean isfind = false;
        if (unitname.equals("EndUnit")) return null;
        List<IwFlow> userList = new ArrayList<IwFlow>();
        userList = iwFlowList.stream().filter(user -> unitname.equals(user.getUnitName())).collect(Collectors.toList());
        if (userList.size() > 0)
            return null;

        List<Element> ActivityNodeList = rootElt.selectNodes("/data/TcxFlow/Objects/TcxFlowConditionBranchUnit");
        for (int i = 0; i <= ActivityNodeList.size() - 1; i++) {
            Element lNodeItem = ActivityNodeList.get(i);
//            System.out.println("00"+unitname);
            if (lNodeItem.selectSingleNode("Name").getStringValue().equals(unitname)) {
                System.out.println("TcxFlowConditionBranchUnit:" + unitname);

                IwFlow iwFlow = new IwFlow();
                iwFlow.setUnittype("TcxFlowConditionBranchUnit");
                iwFlow.setUnitName(lNodeItem.selectSingleNode("Name").getStringValue());

                //temptable.FieldByName('unitcaption').AsString:= lNodeItem.selectSingleNode('Caption').text;
                //
                //            temptable.FieldByName('NextUnit').AsString:= lNodeItem.selectSingleNode('NextUnit').text;
                iwFlow.setUnitcaption(lNodeItem.selectSingleNode("Caption").getStringValue());
                iwFlow.setCondition(lNodeItem.selectSingleNode("Condition").getStringValue());
                if (!StringUtils.isEmpty(lNodeItem.selectSingleNode("TrueUnit")))
                    iwFlow.setTrueUnit(lNodeItem.selectSingleNode("TrueUnit").getStringValue());
                if (!StringUtils.isEmpty(lNodeItem.selectSingleNode("TrueUnit")))
                    iwFlow.setFalseUnit(lNodeItem.selectSingleNode("FalseUnit").getStringValue());
                if (!StringUtils.isEmpty(lNodeItem.selectSingleNode("OnCalcExecutorRange/Script")))
                    iwFlow.setScript(new String(Base64.decode(lNodeItem.selectSingleNode("OnCalcCondition/Script").getStringValue())));

                //iwFlow.setNextUnit(lNodeItem.selectSingleNode("NextUnit").getStringValue());


                if (!StringUtils.isEmpty(lNodeItem.selectSingleNode("RuntimeProperties"))) {
                    iwFlow.setState(lNodeItem.selectSingleNode("RuntimeProperties/State").getStringValue());
                    iwFlow.setLevel(lNodeItem.selectSingleNode("RuntimeProperties/Level").getStringValue());



//                    iwFlow.setExecutor(taskitem.selectSingleNode("Executor").getStringValue());
//                    iwFlow.setSender(taskitem.selectSingleNode("Sender").getStringValue());
                    if (!StringUtils.isEmpty(lNodeItem.selectSingleNode("RuntimeProperties/FlowFromUnits")))
                        iwFlow.setFlowFromUnits(lNodeItem.selectSingleNode("RuntimeProperties/FlowFromUnits").getStringValue());

                }

                iwFlowList.add(iwFlow);
                isfind = true;
                if (!StringUtils.isEmpty(iwFlow.getTrueUnit())) find_nextlevel(rootElt, iwFlow.getTrueUnit());
                if (!StringUtils.isEmpty(iwFlow.getFalseUnit())) find_nextlevel(rootElt, iwFlow.getFalseUnit());
                break;
            }

        }
        if (!isfind) find_nextlevel(rootElt, unitname);
        return iwFlowList;

    }

    public static
    JSONObject readperxml(String xml, String modulename, String OrganizationID, JSONObject json) throws Exception {


        //JSONArray jsonarray=new JSONArray();
//
//        JSONObject json2 =new JSONObject();

//        JSONArray jsonArray1=new JSONArray();
//        JSONArray jsonArray2=new JSONArray();
        JSONArray jsonArray1=json.getJSONArray("roles");
        JSONArray jsonArray2=json.getJSONArray("fields");
        Document doc = DocumentHelper.parseText(xml);
        Element rootElt = doc.getRootElement();
        //System.out.println(rootElt);
        //Node node1= rootElt.selectSingleNode("//data/TcxRolePermissions");
       // System.out.println(node1.getPath()+""+node1.getStringValue()+""+node1.getText());
        //System.exit(0);

        List<Element> nodes = rootElt.selectNodes("//data/TcxRolePermissions/Modules/Item[@Name='"+modulename+"']");
       // System.out.println(nodes);
        if (nodes.size() > 0) {
            Element node = nodes.get(0);

            String Range= node.attribute("Range").getValue();
            //json1.clear();
            JSONObject json1 =new JSONObject();
            json1.put("OrganizationID",OrganizationID);
            json1.put("Range",Range);

            jsonArray1.add(json1);



        }
            nodes = rootElt.selectNodes("/data/TcxRolePermissions/Protections/Item");
        if (nodes.size() > 0) {
            for (int j = 0; j <= nodes.size() - 1; j++) {
                Element node = nodes.get(j);
                String fieldname = node.attribute("Name").getValue();
                if (fieldname.contains(modulename)) {
                    String Mode= node.attribute("Mode").getValue();
                    if (Mode.contains("pmHide")){
                    fieldname = fieldname.replace("Field://", "");
                    JSONObject json1 =new JSONObject();

                    json1.put("fieldname", fieldname);
                    json1.put("Mode", Mode);

                    jsonArray2.add(json1);}

                }

            }
        }
            //json.put("fields",jsonarray);
         return json;




    }
}
